package com.friend.service.user.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.common.core.constants.Constants;
import com.common.core.domain.TableDataInfo;
import com.common.core.domain.dto.PageQueryDTO;
import com.common.core.utils.ThreadLocalUtil;
import com.friend.domain.message.MessageTextVO;
import com.friend.manager.MessageCacheManager;
import com.friend.mapper.message.MessageTextMapper;
import com.friend.service.user.UserMessageService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserMessageServiceImpl implements UserMessageService {

    @Resource
    MessageCacheManager messageCacheManager;

    @Resource
    MessageTextMapper messageTextMapper;

    @Override
    public TableDataInfo list(PageQueryDTO pageQueryDTO) {
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        Long total = messageCacheManager.getListSize(userId);
        List<MessageTextVO> messageTextVOList;
        if (total == null || total <= 0) {
            PageHelper.startPage(pageQueryDTO.getPageNum(), pageQueryDTO.getPageSize());
            //从数据库中查询信息
            messageTextVOList = messageTextMapper.selectUserMsgList(userId);
            //更新Redis中的数据
            messageCacheManager.refreshCache(userId);
            total = new PageInfo<>(messageTextVOList).getTotal();
        } else {
            //从缓存中获取
            messageTextVOList = messageCacheManager.getMsgTextVOList(pageQueryDTO, userId);
        }
        if (CollectionUtil.isEmpty(messageTextVOList)) {
            return TableDataInfo.empty();   //没有数据
        }
        return TableDataInfo.success(messageTextVOList, total);
    }
}
